package com.community.owner.service.impl;

import com.community.common.exception.ServiceException;
import com.community.owner.domain.Resident;
import com.community.owner.domain.vo.Result;
import com.community.owner.handle.exception.MyException;
import com.community.owner.mapper.ResidentMapper;
import com.community.owner.service.ResidentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class ResidentServiceImpl implements ResidentService {

    @Autowired
    private ResidentMapper residentMapper;

    @Override
    public List<Resident> getResidentByOwnerId(Long ownerId) {
        if (ownerId == null){
            throw new ServiceException("业主ID不能为空");
        }else {
            return residentMapper.getResidentByOwnerId(ownerId);
        }
    }


    @Override
    @Transactional
    public Integer batchAddResidents(List<Resident> residentList) {
        StringBuilder errorMsg = new StringBuilder();
        List<Resident> residents = new ArrayList<>();

        for (int i = 0; i < residentList.size(); i++) {
            Resident resident = residentList.get(i);
            int lineNumber = i + 1;
            try {
                // 直接调用 Mapper 方法，不通过 Service 层
                int count = residentMapper.isIdCardExists(resident.getIdCard());
                System.out.println("DEBUG: 身份证号 " + resident.getIdCard() + " 检查结果: " + count);

                if (count > 0) {
                    throw new MyException(Result.fail("身份证号在系统中已存在"));
                }

                residents.add(resident);
            } catch (Exception e) {
                errorMsg.append("第").append(lineNumber).append("行: ").append(e.getMessage()).append("; ");
            }
        }

        if (errorMsg.length() > 0) {
            throw new MyException(Result.fail(errorMsg.toString()));
        }

        int successCount = residentMapper.batchAddResidents(residents);
        return successCount;
    }
    @Override
    public Integer isIdCardExists(String idCard) {
        Integer idCards = residentMapper.isIdCardExists(idCard);
        return idCards;
    }
}
